package com.baifendian.config;

import com.github.pagehelper.PageHelper;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.plugin.Interceptor;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.util.StringUtils;
import org.apache.ibatis.session.SqlSessionFactory;

/**
 * @author peng.guo on 2018/3/5.
 */
@Configuration
public class MybatisConfiguration {

  private static final Log log = LogFactory.getLog(MybatisConfiguration.class);

  /**
   * 获取系统参数
   */
  @Autowired
  private Environment env;

  /**
   * 根据application.properties创建数据远
   * @return
   * @throws Exception
   */
  @Bean
  public DataSource createDataSource() throws Exception{

    ComboPooledDataSource dataSource = new ComboPooledDataSource();
    dataSource.setDriverClass(env.getProperty("jdbc.driver-class-name"));
    dataSource.setJdbcUrl(env.getProperty("jdbc.url"));
    dataSource.setUser(env.getProperty("jdbc.username"));
    dataSource.setPassword(env.getProperty("jdbc.password"));
    dataSource.setInitialPoolSize(
        StringUtils.isEmpty(env.getProperty("jdbc.initialSize")) ? 10 : Integer.valueOf(env.getProperty("jdbc.initialSize")));
    dataSource.setMinPoolSize(StringUtils.isEmpty(env.getProperty("jdbc.minPoolSize")) ? 5 : Integer.valueOf(env.getProperty("jdbc.minPoolSize")));
    dataSource.setMaxPoolSize(StringUtils.isEmpty(env.getProperty("jdbc.maxPoolSize")) ? 30 : Integer.valueOf(env.getProperty("jdbc.maxPoolSize")));

    dataSource.setMaxIdleTime(StringUtils.isEmpty(env.getProperty("jdbc.maxIdleTime")) ? 60 : Integer.valueOf(env.getProperty("jdbc.maxIdleTime")));

    dataSource.setAcquireIncrement(StringUtils.isEmpty(env.getProperty("jdbc.acquireIncrement")) ? 5 : Integer.valueOf(env.getProperty("jdbc.acquireIncrement")));
    dataSource.setIdleConnectionTestPeriod(StringUtils.isEmpty(env.getProperty("jdbc.idleConnectionTestPeriod")) ? 300 : Integer.valueOf(env.getProperty("jdbc.idleConnectionTestPeriod")));
    dataSource.setAcquireRetryAttempts(StringUtils.isEmpty(env.getProperty("jdbc.acquireRetryAttempts")) ? 5 : Integer.valueOf(env.getProperty("jdbc.acquireRetryAttempts")));

    return dataSource;
  }

  @Bean
  public SqlSessionFactory createSqlSessionFactory(DataSource dataSource) throws Exception {

    SqlSessionFactoryBean sfb = new SqlSessionFactoryBean();
    sfb.setDataSource(dataSource);// 指定数据源(这个必须有，否则报错)

    Properties props = new Properties();
    props.setProperty("reasonable", "true");
    props.setProperty("supportMethodsArguments", "true");
    props.setProperty("returnPageInfo", "check");
    props.setProperty("params", "count=countSql");
    props.setProperty("rowBoundsWithCount", "true");

    //分页插件
    PageHelper pageHelper = new PageHelper();
    pageHelper.setProperties(props);

    sfb.setPlugins(new Interceptor[]{pageHelper});

    //添加XML目录
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    try {

      sfb.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
      sfb.setTypeAliasesPackage("com.baifendian.dao.entity");
    } catch (Exception e) {
      e.printStackTrace();
      throw new RuntimeException(e);
    }

    return sfb.getObject();
  }

  @Bean
  public PlatformTransactionManager annotationDrivenTransactionManager(DataSource dataSource) {
    return new DataSourceTransactionManager(dataSource);
  }

}
